﻿using System;
using System.Linq;
using System.Threading;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Hardware;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.OS;
using GBU.Services.Common;

namespace GBU.Services.StepService
{
    [Service]
    [IntentFilter(new string[]{"AcceleraService"})]
    public class AcceleraService:Service
    {
        public override IBinder OnBind(Intent intent)
        {
            return new CommonServiceBinder<AcceleraService>(this);
        }

        private const string Tag = "AcceleraService";
        private SensorManager _sensorManager;
        private AcceleraView _acceleraView;
        private Sensor acceleraSensor;

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Log.Debug(Tag, "AcceleraService Started.");
            //StepingStart();
            //InitSensors();
            //return base.OnStartCommand(intent, flags, startId);
            return StartCommandResult.NotSticky;
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

        public void StepingStart()
        {
            Log.Debug(Tag, "Steping, Started.");
           // Toast.MakeText(this,"StepService Started",ToastLength.Short).Show();
            _sensorManager = (SensorManager) GetSystemService(SensorService);
            _acceleraView=new AcceleraView(this);
            _acceleraView.OnAcceleraChanged += new EventHandler<AccelerationEventArgs>(_acceleraView_OnAcceleraChanged);
             acceleraSensor = _sensorManager.GetDefaultSensor(SensorType.Accelerometer);
            
            _sensorManager.RegisterListener(_acceleraView, acceleraSensor, SensorDelay.Fastest);
        }

        public void StepingStop()
        {
            _sensorManager.UnregisterListener(_acceleraView);
        }

        void _acceleraView_OnAcceleraChanged(object sender, AccelerationEventArgs e)
        {
            Log.Debug(Tag, "Get Acceleration Data and send by broadcast.");
            SendMessage(e.Steps);
        }

        void SendMessage(int step)
        {
                Intent i = new Intent(MessageType.Steping);
                i.PutExtra(MessageType.StepKey, step);
                SendBroadcast(i);
        }

       
    }
}
